<!-- OpenAI Format Evaluations Tab -->
<div id="tabEvalsOpenAI" class="tab-content">
    <div class="endpoint-section" id="evalsCreate">
        <h2>
            <span class="endpoint-method post">POST</span>
            <span class="endpoint-path">/api/v1/evaluations - Create Evaluation</span>
        </h2>
        <p>Create a new evaluation (OpenAI format).</p>

        <div class="form-group">
            <label for="evalsCreate_model">Model:</label>
            <select id="evalsCreate_model" class="llm-model-select">
                <option value="">Loading models...</option>
            </select>
        </div>

        <div class="form-group">
            <label for="evalsCreate_payload">Evaluation Configuration (JSON):</label>
            <textarea id="evalsCreate_payload" class="code-input" rows="15">{
  "name": "Math Problem Solving Eval",
  "description": "Evaluate math problem solving capabilities",
  "dataset_id": "dataset_123",
  "config": {
    "model": "gpt-4o-mini",
    "temperature": 0.1,
    "max_tokens": 1000,
    "metrics": ["accuracy", "reasoning_quality"],
    "eval_type": "classification"
  }
}</textarea>
        </div>

        <button class="api-button" data-req-section="evalsCreate" data-req-method="POST" data-req-path="/api/v1/evaluations" data-req-body-type="json">
            Create Evaluation
        </button>

        <h3>cURL Command:</h3>
        <pre id="evalsCreate_curl">---</pre>

        <h3>Response:</h3>
        <pre id="evalsCreate_response">---</pre>
    </div>

    <div class="endpoint-section" id="evalsRun">
        <h2>
            <span class="endpoint-method post">POST</span>
            <span class="endpoint-path">/api/v1/evaluations/{eval_id}/runs - Start Evaluation Run</span>
        </h2>
        <p>Start a new evaluation run.</p>

        <div class="form-group">
            <label for="evalsRun_id">Evaluation ID <span class="required">*</span>:</label>
            <input type="text" id="evalsRun_id" placeholder="eval_123">
        </div>

        <div class="form-group">
            <label for="evalsRun_config">Run Configuration (JSON):</label>
            <textarea id="evalsRun_config" class="code-input" rows="8">{
  "batch_size": 10,
  "parallel_workers": 4,
  "timeout": 300,
  "retry_failed": true
}</textarea>
        </div>

        <button class="api-button" data-req-section="evalsRun" data-req-method="POST" data-req-path="/api/v1/evaluations/{id}/runs" data-req-body-type="json">
            Start Run
        </button>

        <h3>cURL Command:</h3>
        <pre id="evalsRun_curl">---</pre>

        <h3>Response:</h3>
        <pre id="evalsRun_response">---</pre>
    </div>
</div>

<!-- G-Eval Tab -->
<div id="tabEvalsGEval" class="tab-content">
    <div class="endpoint-section" id="geval">
        <h2>
            <span class="endpoint-method post">POST</span>
            <span class="endpoint-path">/api/v1/evaluations/geval - G-Eval Evaluation</span>
        </h2>
        <p>Perform G-Eval evaluation on generated text.</p>

        <div class="form-group">
            <label for="geval_model">Model:</label>
            <select id="geval_model" class="llm-model-select">
                <option value="">Loading models...</option>
            </select>
        </div>

        <div class="form-group">
            <label for="geval_payload">G-Eval Request (JSON):</label>
            <textarea id="geval_payload" class="code-input" rows="15">{
  "reference": "The capital of France is Paris. It is known for the Eiffel Tower.",
  "candidate": "Paris is the capital city of France, famous for its Eiffel Tower landmark.",
  "criteria": ["coherence", "consistency", "fluency", "relevance"],
  "model": "gpt-4o-mini",
  "temperature": 0.3
}</textarea>
        </div>

        <button class="api-button" data-req-section="geval" data-req-method="POST" data-req-path="/api/v1/evaluations/geval" data-req-body-type="json">
            Run G-Eval
        </button>

        <h3>cURL Command:</h3>
        <pre id="geval_curl">---</pre>

        <h3>Response:</h3>
        <pre id="geval_response">---</pre>
    </div>
</div>

<!-- Load migrated Evals module -->
<script src="js/evals.js"></script>

<!-- RAG Evaluation Tab -->
<div id="tabEvalsRAG" class="tab-content">
    <div class="endpoint-section" id="ragEval">
        <h2>
            <span class="endpoint-method post">POST</span>
            <span class="endpoint-path">/api/v1/evaluations/rag - RAG Evaluation</span>
        </h2>
        <p>Evaluate RAG system performance.</p>

        <div class="form-group">
            <label for="ragEval_payload">RAG Evaluation Request (JSON):</label>
            <textarea id="ragEval_payload" class="code-input" rows="18">{
  "query": "What are the main features of the system?",
  "retrieved_contexts": [
    "The system features include user authentication, data processing, and reporting.",
    "Advanced analytics and real-time monitoring are key capabilities."
  ],
  "generated_answer": "The main features include authentication, data processing, reporting, analytics, and monitoring.",
  "ground_truth": "The system offers authentication, processing, reporting, analytics, and real-time monitoring.",
  "metrics": ["context_relevance", "answer_faithfulness", "answer_relevance"],
  "model": "gpt-4o-mini"
}</textarea>
        </div>

        <h4>Server Presets</h4>
        <div class="form-group">
            <button class="api-button" id="btnRagEvalRefreshPresets">Refresh Presets</button>
            <select id="ragEvalPreset_select" style="min-width: 260px;"></select>
            <button class="api-button" id="btnRagEvalApplyPresetTemplate">Apply Preset as Test Template</button>
        </div>
        <script>
            async function ragEvalRefreshPresets() {
                try {
                    const resp = await apiClient.makeRequest('GET', '/api/v1/evaluations/rag/pipeline/presets');
                    const sel = document.getElementById('ragEvalPreset_select');
                    sel.innerHTML = '';
                    const items = (resp && resp.items) ? resp.items : [];
                    items.forEach(item => {
                        const opt = document.createElement('option');
                        opt.value = item.name;
                        opt.textContent = item.name;
                        sel.appendChild(opt);
                    });
                    Toast.success(`Loaded ${items.length} presets`);
                } catch (e) {
                    Toast.error('Failed to list presets: ' + (e?.message || e));
                }
            }
            async function ragEvalApplyPresetTemplate() {
                try {
                    const sel = document.getElementById('ragEvalPreset_select');
                    const name = sel && sel.value ? sel.value : null;
                    if (!name) { alert('Select a preset first'); return; }
                    const resp = await apiClient.makeRequest('GET', `/api/v1/evaluations/rag/pipeline/presets/${encodeURIComponent(name)}`);
                    if (!(resp && resp.config)) { alert('Preset not found'); return; }
                    const cfg = resp.config;
                    let apiName = 'openai';
                    try {
                        const model = (cfg.rag && (Array.isArray(cfg.rag.model) ? cfg.rag.model[0] : cfg.rag.model)) || '';
                        const m = String(model).toLowerCase();
                        if (m.includes('claude')) apiName = 'anthropic';
                        else if (m.includes('groq')) apiName = 'groq';
                        else if (m.includes('gemini') || m.includes('google')) apiName = 'google';
                        else if (m.includes('mistral')) apiName = 'mistral';
                        else apiName = 'openai';
                    } catch (e) { apiName = 'openai'; }
                    const tmpl = {
                        query: "Your question here",
                        retrieved_contexts: ["Paste or fetch retrieved contexts here"],
                        generated_response: "Your model response here",
                        ground_truth: "Optional gold answer",
                        metrics: ["relevance", "faithfulness", "answer_similarity", "context_precision"],
                        api_name: apiName
                    };
                    const ta = document.getElementById('ragEval_payload');
                    ta.value = JSON.stringify(tmpl, null, 2);
                    Toast.success('Inserted test template from preset. Fill contexts/response and run.');
                } catch (e) {
                    alert('Failed to apply preset to RAG Eval: ' + (e?.message || e));
                }
            }
        </script>

        <button class="api-button" data-req-section="ragEval" data-req-method="POST" data-req-path="/api/v1/evaluations/rag" data-req-body-type="json">
            Run RAG Evaluation
        </button>

        <h3>cURL Command:</h3>
        <pre id="ragEval_curl">---</pre>

        <h3>Response:</h3>
        <pre id="ragEval_response">---</pre>
    </div>
</div>

<!-- RAG Pipeline Evaluation Tab -->
<div id="tabEvalsRAGPipeline" class="tab-content">
    <div class="endpoint-section" id="ragPipelineEval">
        <h2>
            <span class="endpoint-method post">POST</span>
            <span class="endpoint-path">/api/v1/evaluations (rag_pipeline) + /runs</span>
        </h2>
        <p>Create and run a RAG pipeline evaluation using the unified RAG pipeline under the hood.</p>

        <div class="form-group">
            <label for="ragPipelineCreate_payload">Create rag_pipeline Evaluation (JSON):</label>
            <textarea id="ragPipelineCreate_payload" class="code-input" rows="20">{
  "name": "rag_pipeline_demo",
  "eval_type": "model_graded",
  "eval_spec": {
    "sub_type": "rag_pipeline",
    "rag_pipeline": {
      "dataset": [
        {
          "input": {
            "question": "What is X?",
            "corpus": ["X is a thing used in...", "In some docs, X refers to..."]
          },
          "expected": {"answer": "X is ...", "relevant_ids": ["doc_1"]}
        }
      ],
      "index_namespace": "rag_eval_ns",
      "chunking": {"method": ["sentences"], "chunk_size": [512], "overlap": [64]},
      "retrievers": [{"search_mode": ["hybrid"], "hybrid_alpha": [0.3, 0.7], "top_k": [8]}],
      "rerankers": [{"strategy": ["flashrank", "cross_encoder"], "top_k": [5]}],
      "rag": {"model": ["gpt-4o-mini"], "temperature": [0.1], "max_tokens": [256]},
      "search_strategy": "grid",
      "max_trials": 4
    }
  }
}</textarea>
        </div>

        <button class="api-button" data-req-section="ragPipelineCreate" data-req-method="POST" data-req-path="/api/v1/evaluations" data-req-body-type="json">
            Create rag_pipeline Evaluation
        </button>

        <div class="form-group">
            <label for="ragPipelineRun_id">Evaluation ID to Run:</label>
            <input type="text" id="ragPipelineRun_id" placeholder="eval_...">
        </div>

        <div class="form-group">
            <label for="ragPipelineRun_config">Run Config (JSON):</label>
            <textarea id="ragPipelineRun_config" class="code-input" rows="4">{}</textarea>
        </div>

        <button class="api-button" data-req-section="ragPipelineRun" data-req-method="POST" data-req-path="/api/v1/evaluations/{id}/runs" data-req-body-type="json">
            Start Run
        </button>

        <h3>Responses:</h3>
        <pre id="ragPipelineCreate_response">---</pre>
        <pre id="ragPipelineRun_response">---</pre>

        <div class="text-small" style="margin-top:10px;">
            Quick samples: <a href="/docs-static/Evals/samples/README.md" target="_blank" rel="noopener">Docs/Evals/samples</a>
        </div>

        <div class="form-group" style="margin-top:10px;">
          <button class="api-button" id="btnRagPipelineRenderLeaderboard">Render Leaderboard Preview</button>
          <button class="api-button" id="btnRagPipelineExportCsv">Export Leaderboard CSV</button>
          <button class="api-button" id="btnRagPipelineExportPerConfigCsv">Export Per-Config CSV</button>
        </div>
        <div id="ragPipelineRun_preview" style="overflow:auto; max-height:320px; border:1px solid var(--color-border); padding:8px; border-radius:6px; background: var(--color-surface-alt);"></div>

        <h3>Best Config Preset</h3>
        <div class="form-group">
            <button class="api-button" id="btnExtractBestConfig">Extract Best Config From Last Run</button>
            <button class="api-button" id="btnApplyBestConfigToCreate">Apply Best Config to Create Payload</button>
        </div>
        <div class="form-group">
            <label for="ragPipelinePreset_name">Preset Name:</label>
            <input type="text" id="ragPipelinePreset_name" placeholder="my-best-preset" value="rag_pipeline_best">
        </div>
        <div class="form-group">
            <label for="ragPipelinePreset_json">Best Config JSON:</label>
            <textarea id="ragPipelinePreset_json" class="code-input" rows="8" placeholder="{\n  &quot;chunking&quot;: {...},\n  &quot;retriever&quot;: {...},\n  &quot;reranker&quot;: {...},\n  &quot;rag&quot;: {...}\n}"></textarea>
        </div>
        <div class="form-group">
            <button class="api-button" id="btnSaveRagPipelinePreset">Save Preset</button>
            <button class="api-button" id="btnApplyPresetToCreate">Apply Preset to Create Payload</button>
            <button class="api-button" id="btnSavePresetToServer">Save Preset (Server)</button>
            <button class="api-button" id="btnLoadPresetFromServer">Load Preset (Server)</button>
        </div>

        <h4>Server Presets</h4>
        <div class="form-group">
            <button class="api-button" id="btnRefreshServerPresets">Refresh Presets</button>
            <select id="ragPipelinePreset_select" style="min-width: 240px;"></select>
            <button class="api-button" id="btnApplySelectedServerPreset">Apply Selected to Create Payload</button>
        </div>

        <script>
            function extractBestConfigFromRun() {
                try {
                    const pre = document.getElementById('ragPipelineRun_response');
                    const text = pre ? pre.textContent.trim() : '';
                    const obj = JSON.parse(text);
                    const best = obj && (obj.best_config || (obj.results && obj.results.best_config));
                    if (!best) { alert('best_config not found in response'); return; }
                    const cfg = best.config || best;
                    document.getElementById('ragPipelinePreset_json').value = JSON.stringify(cfg, null, 2);
                    Toast.success('Best config extracted.');
                } catch (e) {
                    alert('Could not parse run response as JSON. Try copying best_config manually.');
                }
            }
            function saveRagPipelinePreset() {
                const name = (document.getElementById('ragPipelinePreset_name').value || 'rag_pipeline_best').trim();
                const text = document.getElementById('ragPipelinePreset_json').value;
                try {
                    const cfg = JSON.parse(text);
                    localStorage.setItem('ragPipelinePreset_' + name, JSON.stringify(cfg));
                    Toast.success('Preset saved as ' + name);
                } catch (e) {
                    alert('Invalid JSON for preset: ' + e.message);
                }
            }
            function applyPresetToCreatePayload() {
                const name = (document.getElementById('ragPipelinePreset_name').value || 'rag_pipeline_best').trim();
                const presetRaw = localStorage.getItem('ragPipelinePreset_' + name);
                if (!presetRaw) { alert('Preset not found: ' + name); return; }
                try {
                    const preset = JSON.parse(presetRaw);
                    const ta = document.getElementById('ragPipelineCreate_payload');
                    const obj = JSON.parse(ta.value);
                    const rp = (((obj || {}).eval_spec || {}).rag_pipeline || {});
                    // Merge preset blocks
                    rp.chunking = preset.chunking || rp.chunking;
                    rp.retrievers = preset.retriever ? [preset.retriever] : (rp.retrievers || []);
                    rp.rerankers = preset.reranker ? [preset.reranker] : (rp.rerankers || []);
                    rp.rag = preset.rag || rp.rag;
                    obj.eval_spec = obj.eval_spec || {};
                    obj.eval_spec.rag_pipeline = rp;
                    ta.value = JSON.stringify(obj, null, 2);
                    Toast.success('Preset applied to create payload.');
                } catch (e) {
                    alert('Failed to apply preset: ' + e.message);
                }
            }
            async function savePresetToServer() {
                try {
                    const name = (document.getElementById('ragPipelinePreset_name').value || 'rag_pipeline_best').trim();
                    const text = document.getElementById('ragPipelinePreset_json').value;
                    const cfg = JSON.parse(text);
                    const body = { name, config: cfg };
                    const resp = await apiClient.makeRequest('POST', '/api/v1/evaluations/rag/pipeline/presets', { body });
                    if (resp && resp.name) {
                        Toast.success('Preset saved on server: ' + resp.name);
                    } else {
                        Toast.error('Server did not confirm preset save.');
                    }
                } catch (e) {
                    alert('Failed to save preset to server: ' + (e?.message || e));
                }
            }
            async function loadPresetFromServer() {
                try {
                    const name = (document.getElementById('ragPipelinePreset_name').value || 'rag_pipeline_best').trim();
                    const resp = await apiClient.makeRequest('GET', `/api/v1/evaluations/rag/pipeline/presets/${encodeURIComponent(name)}`);
                    if (resp && resp.config) {
                        document.getElementById('ragPipelinePreset_json').value = JSON.stringify(resp.config, null, 2);
                        Toast.success('Preset loaded from server.');
                    } else {
                        Toast.error('Preset not found on server.');
                    }
                } catch (e) {
                    alert('Failed to load preset from server: ' + (e?.message || e));
                }
            }
            async function refreshServerPresets() {
                try {
                    const resp = await apiClient.makeRequest('GET', '/api/v1/evaluations/rag/pipeline/presets');
                    const sel = document.getElementById('ragPipelinePreset_select');
                    sel.innerHTML = '';
                    const items = (resp && resp.items) ? resp.items : [];
                    items.forEach(item => {
                        const opt = document.createElement('option');
                        opt.value = item.name;
                        opt.textContent = item.name;
                        sel.appendChild(opt);
                    });
                    Toast.success(`Loaded ${items.length} presets`);
                } catch (e) {
                    alert('Failed to list presets: ' + (e?.message || e));
                }
            }
            async function applySelectedServerPreset() {
                try {
                    const sel = document.getElementById('ragPipelinePreset_select');
                    const name = sel && sel.value ? sel.value : null;
                    if (!name) { alert('Select a preset first'); return; }
                    const resp = await apiClient.makeRequest('GET', `/api/v1/evaluations/rag/pipeline/presets/${encodeURIComponent(name)}`);
                    if (!(resp && resp.config)) { alert('Preset not found'); return; }
                    const ta = document.getElementById('ragPipelineCreate_payload');
                    const obj = JSON.parse(ta.value);
                    const rp = (((obj || {}).eval_spec || {}).rag_pipeline || {});
                    rp.chunking = resp.config.chunking || rp.chunking;
                    rp.retrievers = resp.config.retriever ? [resp.config.retriever] : (rp.retrievers || []);
                    rp.rerankers = resp.config.reranker ? [resp.config.reranker] : (rp.rerankers || []);
                    rp.rag = resp.config.rag || rp.rag;
                    obj.eval_spec = obj.eval_spec || {};
                    obj.eval_spec.rag_pipeline = rp;
                    ta.value = JSON.stringify(obj, null, 2);
                    Toast.success('Applied selected preset to create payload.');
                } catch (e) {
                    alert('Failed to apply preset: ' + (e?.message || e));
                }
            }
        </script>

        <h3>Tip:</h3>
        <p>When the run completes, the results include a <code>leaderboard</code> and <code>best_config</code> with the winning configuration. You can copy these settings to your RAG defaults.</p>
    </div>
</div>

<!-- RAG Pipeline Presets Tab -->
<div id="tabEvalsRAGPresets" class="tab-content">
  <div class="endpoint-section" id="ragPresetList">
    <h2>
      <span class="endpoint-method get">GET</span>
      <span class="endpoint-path">/api/v1/evaluations/rag/pipeline/presets - List Presets</span>
    </h2>
    <p>List saved RAG pipeline presets.</p>
    <button class="api-button" data-req-section="ragPresetList" data-req-method="GET" data-req-path="/api/v1/evaluations/rag/pipeline/presets" data-req-body-type="none">List Presets</button>
    <h3>Response:</h3>
    <pre id="ragPresetList_response">---</pre>
  </div>

  <div class="endpoint-section" id="ragPresetGet">
    <h2>
      <span class="endpoint-method get">GET</span>
      <span class="endpoint-path">/api/v1/evaluations/rag/pipeline/presets/{name} - Get Preset</span>
    </h2>
    <div class="form-group">
      <label for="ragPresetGet_name">Preset Name <span class="required">*</span>:</label>
      <input type="text" id="ragPresetGet_name" placeholder="rag_pipeline_best">
    </div>
    <button class="api-button" data-req-section="ragPresetGet" data-req-method="GET" data-req-path="/api/v1/evaluations/rag/pipeline/presets/{name}" data-req-body-type="none">Get Preset</button>
    <h3>Response:</h3>
    <pre id="ragPresetGet_response">---</pre>
  </div>

  <div class="endpoint-section" id="ragPresetDelete">
    <h2>
      <span class="endpoint-method delete">DELETE</span>
      <span class="endpoint-path">/api/v1/evaluations/rag/pipeline/presets/{name} - Delete Preset</span>
    </h2>
    <div class="form-group">
      <label for="ragPresetDelete_name">Preset Name <span class="required">*</span>:</label>
      <input type="text" id="ragPresetDelete_name" placeholder="rag_pipeline_best">
    </div>
    <button class="api-button btn-danger" data-req-section="ragPresetDelete" data-req-method="DELETE" data-req-path="/api/v1/evaluations/rag/pipeline/presets/{name}" data-req-body-type="none" data-confirm="Delete preset?">Delete Preset</button>
    <h3>Response:</h3>
    <pre id="ragPresetDelete_response">---</pre>
  </div>
</div>

<!-- Evaluation Runs Tab -->
<div id="tabEvalsRuns" class="tab-content">
  <div class="endpoint-section" id="evalRunsList">
    <h2>
      <span class="endpoint-method get">GET</span>
      <span class="endpoint-path">/api/v1/evaluations/{id}/runs - List Runs</span>
    </h2>
    <p>List runs for a specific evaluation.</p>
    <div class="form-group">
      <label for="evalRunsList_id">Evaluation ID <span class="required">*</span>:</label>
      <input type="text" id="evalRunsList_id" placeholder="eval_...">
    </div>
    <button class="api-button" data-req-section="evalRunsList" data-req-method="GET" data-req-path="/api/v1/evaluations/{id}/runs" data-req-body-type="none">List Runs</button>
    <h3>Response:</h3>
    <pre id="evalRunsList_response">---</pre>
  </div>

  <div class="endpoint-section" id="evalRunGet">
    <h2>
      <span class="endpoint-method get">GET</span>
      <span class="endpoint-path">/api/v1/evaluations/runs/{run_id} - Get Run</span>
    </h2>
    <div class="form-group">
      <label for="evalRunGet_run_id">Run ID <span class="required">*</span>:</label>
      <input type="text" id="evalRunGet_run_id" placeholder="run_...">
    </div>
    <button class="api-button" data-req-section="evalRunGet" data-req-method="GET" data-req-path="/api/v1/evaluations/runs/{run_id}" data-req-body-type="none">Get Run</button>
    <h3>Response:</h3>
    <pre id="evalRunGet_response">---</pre>
    <div class="form-group" style="margin-top:10px;">
      <button class="api-button" id="btnEvalRunRenderLeaderboard">Render Leaderboard Preview</button>
      <button class="api-button" id="btnEvalRunExportCsv">Export Leaderboard CSV</button>
      <button class="api-button" id="btnEvalRunExportPerConfigCsv">Export Per-Config CSV</button>
    </div>
    <div id="evalRunGet_preview" style="overflow:auto; max-height:320px; border:1px solid var(--color-border); padding:8px; border-radius:6px; background: var(--color-surface-alt);"></div>

    <h3 style="margin-top:12px;">Save Best Config as Preset</h3>
    <div class="form-group">
      <label for="evalRunPreset_name">Preset Name:</label>
      <input type="text" id="evalRunPreset_name" placeholder="rag_pipeline_best">
      <button class="api-button" id="btnEvalRunSaveBestPreset">Save Best Config (Server)</button>
      <button class="api-button" id="btnEvalRunSaveBestPresetLocal">Save Best Config (Local)</button>
    </div>

    <h3 style="margin-top:12px;">Use Local Preset</h3>
    <div class="form-group">
      <button class="api-button" id="btnEvalRunLocalPresetRefresh">Refresh</button>
      <select id="evalRunLocalPreset_select" style="min-width: 240px;"></select>
      <button class="api-button" id="btnEvalRunApplyLocalPreset">Apply Selected to Create Payload</button>
    </div>
  </div>
</div>

<!-- Datasets Tab -->
<div id="tabEvalsDatasets" class="tab-content">
    <div class="endpoint-section" id="datasetsCreate">
        <h2>
            <span class="endpoint-method post">POST</span>
            <span class="endpoint-path">/api/v1/evaluations/datasets - Create Dataset</span>
        </h2>
        <p>Create a new evaluation dataset.</p>

        <div class="form-group">
            <label for="datasetsCreate_payload">Dataset Configuration (JSON):</label>
            <textarea id="datasetsCreate_payload" class="code-input" rows="12">{
  "name": "QA Benchmark Dataset",
  "description": "Question-answering benchmark for testing",
  "type": "qa_pairs",
  "data": [
    {
      "question": "What is the capital of France?",
      "answer": "Paris",
      "metadata": {"difficulty": "easy"}
    }
  ]
}</textarea>
        </div>

        <button class="api-button" data-req-section="datasetsCreate" data-req-method="POST" data-req-path="/api/v1/evaluations/datasets" data-req-body-type="json">
            Create Dataset
        </button>

        <h3>cURL Command:</h3>
        <pre id="datasetsCreate_curl">---</pre>

        <h3>Response:</h3>
        <pre id="datasetsCreate_response">---</pre>
    </div>

    <div class="endpoint-section" id="datasetsList">
        <h2>
            <span class="endpoint-method get">GET</span>
            <span class="endpoint-path">/api/v1/evaluations/datasets - List Datasets</span>
        </h2>
        <p>List all evaluation datasets.</p>

        <button class="api-button" data-req-section="datasetsList" data-req-method="GET" data-req-path="/api/v1/evaluations/datasets" data-req-body-type="none">
            List Datasets
        </button>

        <h3>cURL Command:</h3>
        <pre id="datasetsList_curl">---</pre>

        <h3>Response:</h3>
        <pre id="datasetsList_response">---</pre>
    </div>
</div>

<!-- Response Quality Evaluation Tab -->
<div id="tabEvalsResponseQuality" class="tab-content">
    <div class="endpoint-section" id="responseQualityEval">
        <h2>
            <span class="endpoint-method post">POST</span>
            <span class="endpoint-path">/api/v1/evaluations/response-quality - Response Quality Evaluation</span>
        </h2>
        <p>Evaluate the quality of model responses.</p>

        <div class="form-group">
            <label for="responseQuality_payload">Response Quality Request (JSON):</label>
            <textarea id="responseQuality_payload" class="code-input" rows="15">{
  "prompt": "Explain quantum computing in simple terms",
  "response": "Quantum computing uses quantum bits or qubits that can be in multiple states simultaneously, unlike classical bits that are either 0 or 1.",
  "reference_response": "Quantum computing leverages quantum mechanical phenomena like superposition and entanglement to process information in fundamentally different ways than classical computers.",
  "criteria": {
    "accuracy": 0.3,
    "completeness": 0.3,
    "clarity": 0.2,
    "relevance": 0.2
  },
  "model": "gpt-4o-mini"
}</textarea>
        </div>

        <button class="api-button" data-req-section="responseQualityEval" data-req-method="POST" data-req-path="/api/v1/evaluations/response-quality" data-req-body-type="json">Evaluate Response Quality</button>

        <h3>cURL Command:</h3>
        <pre id="responseQualityEval_curl">---</pre>

        <h3>Response:</h3>
        <pre id="responseQualityEval_response">---</pre>
    </div>
</div>

<!-- OCR Evaluation Tab -->
<div id="tabEvalsOCR" class="tab-content">
  <div class="endpoint-section" id="ocrEval">
    <h2>
      <span class="endpoint-method post">POST</span>
      <span class="endpoint-path">/api/v1/evaluations/ocr - OCR Text Evaluation</span>
    </h2>
    <p>Evaluate OCR effectiveness by comparing extracted text to ground-truth.</p>

    <div class="form-group">
      <label for="ocrEval_payload">OCR Evaluation Request (JSON):</label>
      <textarea id="ocrEval_payload" class="code-input" rows="14">{
  "items": [
    { "id": "doc1", "extracted_text": "Hello world", "ground_truth_text": "Hello world" }
  ],
  "metrics": ["cer", "wer", "coverage", "page_coverage"],
  "thresholds": { "max_cer": 0.1, "max_wer": 0.2 }
}</textarea>
    </div>

    <button class="api-button" data-req-section="ocrEval" data-req-method="POST" data-req-path="/api/v1/evaluations/ocr" data-req-body-type="json">Run OCR Text Eval</button>

    <h3>cURL Command:</h3>
    <pre id="ocrEval_curl">---</pre>

    <h3>Response:</h3>
    <pre id="ocrEval_response">---</pre>
  </div>

  <div class="endpoint-section" id="ocrEvalPdf">
    <h2>
      <span class="endpoint-method post">POST</span>
      <span class="endpoint-path">/api/v1/evaluations/ocr-pdf - OCR PDF Evaluation</span>
    </h2>
    <p>Upload PDFs, run OCR, and compare to provided ground-truths.</p>

    <div class="form-row">
      <div class="column">
        <div class="form-group">
          <label for="ocrEvalPdf_files">PDF Files:</label>
          <input type="file" id="ocrEvalPdf_files" multiple accept=".pdf">
          <small>You can upload multiple PDFs</small>
        </div>

        <div class="form-group">
          <label for="ocrEvalPdf_ground_truths_json">Ground Truths (JSON Array):</label>
          <textarea id="ocrEvalPdf_ground_truths_json" rows="4" placeholder='["GT for file1","GT for file2"]'></textarea>
        </div>

        <div class="form-group">
          <label for="ocrEvalPdf_thresholds_json">Thresholds (JSON):</label>
          <textarea id="ocrEvalPdf_thresholds_json" rows="3" placeholder='{"max_cer":0.15,"min_coverage":0.7}'></textarea>
        </div>
      </div>
      <div class="column">
        <h4>OCR Options</h4>
        <div class="form-group"><label><input type="checkbox" id="ocrEvalPdf_enable_ocr" checked> Enable OCR</label></div>
        <div class="form-group"><label for="ocrEvalPdf_ocr_backend">OCR Backend:</label><input type="text" id="ocrEvalPdf_ocr_backend" placeholder="tesseract or auto"></div>
        <div class="form-group"><label for="ocrEvalPdf_ocr_lang">OCR Lang:</label><input type="text" id="ocrEvalPdf_ocr_lang" value="eng"></div>
        <div class="form-group"><label for="ocrEvalPdf_ocr_dpi">OCR DPI:</label><input type="number" id="ocrEvalPdf_ocr_dpi" value="300" min="72" max="600"></div>
        <div class="form-group"><label for="ocrEvalPdf_ocr_mode">OCR Mode:</label><input type="text" id="ocrEvalPdf_ocr_mode" value="fallback" placeholder="fallback or always"></div>
        <div class="form-group"><label for="ocrEvalPdf_ocr_min_page_text_chars">Min Page Text Chars:</label><input type="number" id="ocrEvalPdf_ocr_min_page_text_chars" value="40" min="0"></div>
      </div>
    </div>

    <div class="form-group">
      <label for="ocrEvalPdf_ground_truths_pages_json">Per-Page Ground Truths (JSON Array of Arrays):</label>
      <textarea id="ocrEvalPdf_ground_truths_pages_json" rows="4" placeholder='[["p1 text","p2 text"], ["p1 text","p2 text"]]'></textarea>
      <small>Optional: provides page-level ground truth for per-page CER/WER scoring</small>
    </div>

    <button class="api-button" data-req-section="ocrEvalPdf" data-req-method="POST" data-req-path="/api/v1/evaluations/ocr-pdf" data-req-body-type="form">Run OCR PDF Eval</button>

    <h3>cURL Command:</h3>
    <pre id="ocrEvalPdf_curl">---</pre>

    <h3>Response:</h3>
    <pre id="ocrEvalPdf_response">---</pre>
  </div>
</div>

<!-- Evaluation Management Tab -->
<div id="tabEvalsManagement" class="tab-content">
    <div class="endpoint-section" id="evalsList">
        <h2>
            <span class="endpoint-method get">GET</span>
            <span class="endpoint-path">/api/v1/evaluations - List Evaluations</span>
        </h2>
        <p>List all evaluations with optional filtering.</p>

        <div class="form-group">
            <label for="evalsList_status">Status:</label>
            <select id="evalsList_status">
                <option value="">All</option>
                <option value="pending">Pending</option>
                <option value="running">Running</option>
                <option value="completed">Completed</option>
                <option value="failed">Failed</option>
            </select>
        </div>

        <div class="form-group">
            <label for="evalsList_limit">Limit:</label>
            <input type="number" id="evalsList_limit" placeholder="10" value="10">
        </div>

        <button class="api-button" data-req-section="evalsList" data-req-method="GET" data-req-path="/api/v1/evaluations" data-req-body-type="query">
            List Evaluations
        </button>

        <h3>Response:</h3>
        <pre id="evalsList_response">---</pre>
    </div>

    <div class="endpoint-section" id="evalsGet">
        <h2>
            <span class="endpoint-method get">GET</span>
            <span class="endpoint-path">/api/v1/evaluations/{eval_id} - Get Evaluation</span>
        </h2>
        <p>Get details of a specific evaluation.</p>

        <div class="form-group">
            <label for="evalsGet_id">Evaluation ID <span class="required">*</span>:</label>
            <input type="text" id="evalsGet_id" placeholder="eval_123">
        </div>

        <button class="api-button" data-req-section="evalsGet" data-req-method="GET" data-req-path="/api/v1/evaluations/{id}" data-req-body-type="none">
            Get Evaluation
        </button>

        <h3>Response:</h3>
        <pre id="evalsGet_response">---</pre>
    </div>

    <div class="endpoint-section" id="evalsUpdate">
        <h2>
            <span class="endpoint-method patch">PATCH</span>
            <span class="endpoint-path">/api/v1/evaluations/{eval_id} - Update Evaluation</span>
        </h2>
        <p>Update an existing evaluation.</p>

        <div class="form-group">
            <label for="evalsUpdate_id">Evaluation ID <span class="required">*</span>:</label>
            <input type="text" id="evalsUpdate_id" placeholder="eval_123">
        </div>

        <div class="form-group">
            <label for="evalsUpdate_payload">Update Data (JSON):</label>
            <textarea id="evalsUpdate_payload" class="code-input" rows="8">{
  "description": "Updated description",
  "config": {
    "temperature": 0.2,
    "max_tokens": 1500
  }
}</textarea>
        </div>

        <button class="api-button" data-req-section="evalsUpdate" data-req-method="PATCH" data-req-path="/api/v1/evaluations/{id}" data-req-body-type="json">
            Update Evaluation
        </button>

        <h3>Response:</h3>
        <pre id="evalsUpdate_response">---</pre>
    </div>

    <div class="endpoint-section" id="evalsDelete">
        <h2>
            <span class="endpoint-method delete">DELETE</span>
            <span class="endpoint-path">/api/v1/evaluations/{eval_id} - Delete Evaluation</span>
        </h2>
        <p>Delete an evaluation and all its runs.</p>

        <div class="form-group">
            <label for="evalsDelete_id">Evaluation ID <span class="required">*</span>:</label>
            <input type="text" id="evalsDelete_id" placeholder="eval_123">
        </div>

        <button class="api-button btn-danger" data-req-section="evalsDelete" data-req-method="DELETE" data-req-path="/api/v1/evaluations/{id}" data-req-body-type="none" data-confirm="Are you sure you want to delete this evaluation?">
            Delete Evaluation
        </button>

        <h3>Response:</h3>
        <pre id="evalsDelete_response">---</pre>
    </div>

    <div class="endpoint-section" id="rateLimits">
        <h2>
            <span class="endpoint-method get">GET</span>
            <span class="endpoint-path">/api/v1/evaluations/rate-limits - Rate Limit Status</span>
        </h2>
        <p>Check current rate limit status for evaluations.</p>

        <button class="api-button" data-req-section="rateLimits" data-req-method="GET" data-req-path="/api/v1/evaluations/rate-limits" data-req-body-type="none">
            Check Rate Limits
        </button>

        <h3>Response:</h3>
        <pre id="rateLimits_response">---</pre>
    </div>
</div>

<script>
// Update evaluation JSON when model is selected
function updateEvalsCreateJSON() {
    const modelSelect = document.getElementById('evalsCreate_model');
    const payloadTextarea = document.getElementById('evalsCreate_payload');

    if (!modelSelect || !payloadTextarea) return;

    try {
        const payload = JSON.parse(payloadTextarea.value);
        if (modelSelect.value) {
            // Extract just the model name from provider/model format
            const modelName = modelSelect.value.split('/').pop();
            payload.config.model = modelName;
            payloadTextarea.value = JSON.stringify(payload, null, 2);
        }
    } catch (e) {
        console.error('Error updating evaluation JSON:', e);
    }
}

function updateGEvalJSON() {
    const modelSelect = document.getElementById('geval_model');
    const payloadTextarea = document.getElementById('geval_payload');

    if (!modelSelect || !payloadTextarea) return;

    try {
        const payload = JSON.parse(payloadTextarea.value);
        if (modelSelect.value) {
            // Extract just the model name from provider/model format
            const modelName = modelSelect.value.split('/').pop();
            payload.model = modelName;
            payloadTextarea.value = JSON.stringify(payload, null, 2);
        }
    } catch (e) {
        console.error('Error updating G-Eval JSON:', e);
    }
}

// Initialize evaluations tab
function initializeEvaluationsTab() {
    console.log('Evaluations tab initialized');
    // Populate model dropdowns when tab is initialized
    populateModelDropdowns();
}

// Call initialization when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    // Check if we're on the evaluations tab
    if (document.querySelector('#tabEvalsOpenAI') || document.querySelector('#tabEvalsGEval')) {
        setTimeout(() => {
            populateModelDropdowns();
        }, 500);
    }
});
</script>
